﻿
using Evan.Model;
using MySql.Data.MySqlClient;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace Evan.DataBase.MySql
{
    /// <summary>
    /// 
    /// </summary>
    public class DbOperat : IDbOperat
    {


        #region 构造函数

        /// <summary>
        /// MYSQL数据操作底层
        /// </summary>
        DbHelper dbHelper;

        /// <summary>
        /// MYSQL
        /// 初始化一个数据操作类 
        /// 使用 默认 链接字符串
        /// </summary>
        public DbOperat()
        {
            dbHelper = new DbHelper();
            this._DataBase = dbHelper.curDataBase;
            this._ConnString = dbHelper.connectionString;
            this._ConnName = dbHelper.curConnName;
        }

        /// <summary>
        /// MYSQL
        /// 初始化一个数据操作类 
        /// 使用 指定 链接字符串名称 (非连接字符串)
        /// </summary>
        /// <param name="ConnName"></param>
        public DbOperat(string ConnName)
        {
            dbHelper = new DbHelper(ConnName);
            this._DataBase = dbHelper.curDataBase;
            this._ConnString = dbHelper.connectionString;
            this._ConnName = dbHelper.curConnName;
        }

        #endregion

        #region 公有属性
        private string _TableName = "";
        public string TableName
        {
            set { _TableName = value; }
            get { return this._TableName; }
        }
        private string _DataBase;
        public string DataBase
        {
            get { return this._DataBase; }
        }
        private string _ConnString;
        public string ConnString
        {
            get { return this._ConnString; }
        }
        private string _ConnName;
        public string ConnName
        {
            get { return this._ConnName; }
        }
        #endregion

        #region 设置操作表
        /// <summary>
        /// 链式操作设置操作表
        /// </summary>
        /// <param name="tabName"></param>
        /// <returns></returns>
        public DataBase.DbOperat SetTable(DataBase.DbOperat dbOperat, string tabName)
        {
            dbOperat.TableName = tabName;
            return dbOperat;
        }
        #endregion


        #region GetModel 方法

        /// <summary>
        /// 获取当前实例对象后的某个表中的所有字段 通过ID
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public dynamic GetModel(string TableName, int Id)
        {
            return GetModelField(TableName, null, "Id=@Id", Id);
        }

        /// <summary>
        /// 获取当前实例对象后的指定表中的指定字段 通过ID
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Fields"></param>
        /// <returns></returns>
        public dynamic GetModelSomeField(string TableName, int Id, string Fields)
        {
            return GetModelField(TableName, Fields, "Id=@Id", Id);
        }

        /// <summary>
        /// 通过Where 获取单条数据
        /// </summary>
        /// <param name="Where">where 语句  注意 : 不用写where</param>
        /// <param name="param">参数列表</param>
        /// <returns></returns>
        public dynamic GetModel(string TableName, string Where, params object[] param)
        {
            return GetModelField(TableName, null, Where, param);
        }

        /// <summary>
        /// 通过Where 获取单条数据
        /// </summary>
        /// <param name="Fields">字段名 Id,Title</param>
        /// <param name="Where">where 语句  注意 : 不用写where</param>
        /// <param name="param">参数列表</param>
        /// <returns></returns>
        public dynamic GetModelSomeField(string TableName, string Fields, string Where, params object[] param)
        {
            return GetModelField(TableName, Fields, Where, param);
        }

        /// <summary>
        /// 获取 单条中的部分字段
        /// </summary>
        /// <param name="TableName">指定表名</param>
        /// <param name="Fields">指定获取那些字段</param>
        /// <param name="Where">Where 条件</param>
        /// <param name="param">参数列表</param>
        /// <returns></returns>
        private dynamic GetModelField(string TableName, string Fields, string Where, params object[] param)
        {
            try
            {
                string SqlStr = string.Format("SELECT {0} FROM {1} WHERE {2}", string.IsNullOrEmpty(Fields) ? "*" : Fields, TableName, Where);
                MySqlParameter[] parameter = dbHelper.GetSqlParameterBySqlStr(SqlStr, param);
                DataRow dr = dbHelper.GetSingle(SqlStr, parameter);
                dynamic Model = null;
                if (dr != null)
                {
                    Model = new DynamicModel();
                    //ArrayList arrList = LoadDbSchema.GetColsByTab(string.IsNullOrEmpty(DataBase) ? this.DataBase : DataBase, TableName);
                    ArrayList arrList = new ArrayList();
                    foreach (var item in dr.Table.Columns)
                    {
                        arrList.Add(item.ToString());
                    }

                    foreach (string item in arrList)
                    {
                        Model.Set(item, dr[item]);
                    }
                }
                return Model;
            }
            catch (Exception ex)
            {
                Debug("获取单条数据GetModel 失败 , 调用方法名 : GetModelField", ex);
                throw ex;
            }
        }
        #endregion

        #region GetList 方法

        /// <summary>
        /// 获取列表方法
        /// </summary>
        /// <param name="Where">条件</param>
        /// <returns></returns>
        public List<dynamic> GetList(string TableName, string Where)
        {
            return GetListField(TableName, 0, null, Where, null, null);
        }

        /// <summary>
        /// 获取列表方法
        /// </summary>
        /// <param name="Top">前几条</param>
        /// <param name="Where">条件</param>
        /// <returns></returns>
        public List<dynamic> GetList(string TableName, int Top, string Where)
        {
            return GetListField(TableName, Top, null, Where, null, null);
        }

        /// <summary>
        /// 获取列表方法
        /// </summary>
        /// <param name="Where">条件</param>
        /// <param name="Order">排序</param>
        /// <returns></returns>
        public List<dynamic> GetList(string TableName, string Where, string Order)
        {
            return GetListField(TableName, 0, null, Where, Order, null);
        }

        /// <summary>
        /// 获取列表方法
        /// </summary>
        /// <param name="Top">前几条</param>
        /// <param name="Where">条件</param>
        /// <param name="Order">排序</param>
        /// <param name="param">参数化语句的参数</param>
        /// <returns></returns>
        public List<dynamic> GetList(string TableName, int Top, string Where, string Order, params object[] param)
        {
            return GetListField(TableName, Top, null, Where, Order, param);
        }


        /// <summary>
        /// 获取列表方法
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="Top">前几条</param>
        /// <param name="Fields">那些字段</param>
        /// <param name="Where">条件</param>
        /// <param name="Order">排序</param>
        /// <param name="param">参数化语句的参数</param>
        /// <returns></returns>
        public List<dynamic> GetListSomeField(string TableName, int Top, string Fields, string Where, string Order, params object[] param)
        {
            return GetListField(TableName, Top, Fields, Where, Order, param);
        }


        private List<dynamic> GetListField(string TableName, int Top, string Fields, string Where, string Order, params object[] param)
        {
            try
            {
                #region 定时发布时间控制
                if (new BLL.Base().GetHasReleaseTime(TableName))
                {
                    //如果表支持定时发布 , 不用理会是否栏目支持定时发布 , 因为表中默认时间和发布时间是一样的
                    if (string.IsNullOrEmpty(Where))
                    {
                        Where = " ReleaseTime<=NOW() ";
                    }
                    else
                    {
                        Where = Where + " and  ReleaseTime<=NOW() ";
                    }
                }
                #endregion

                string SqlStr = string.Format("SELECT {1} FROM {2} WHERE {3} ORDER BY {4} {0} ",
                    Top > 0 ? " LIMIT " + Top : "",
                    string.IsNullOrEmpty(Fields) ? "*" : Fields,
                    TableName,
                    string.IsNullOrEmpty(Where) ? "1=1" : Where,
                    string.IsNullOrEmpty(Order) ? "Id asc" : Order
                    );
                MySqlParameter[] parameter = dbHelper.GetSqlParameterBySqlStr(SqlStr, param);

                DataTable dataTable = dbHelper.GetFirstTable(SqlStr, parameter);
                if (dataTable != null)
                {
                    ArrayList arrList = new ArrayList();
                    if (string.IsNullOrEmpty(Fields))
                    {
                        foreach (var item in dataTable.Columns)
                        {
                            arrList.Add(item.ToString());
                        }
                    }
                    else
                    {
                        string[] arrList_Temp = Fields.Split(',');
                        arrList = new ArrayList(arrList_Temp);
                    }

                    List<dynamic> List = new List<dynamic>();
                    dynamic Model = null;
                    foreach (DataRow item in dataTable.Rows)
                    {
                        Model = new DynamicModel();
                        for (int i = 0; i < arrList.Count; i++)
                        {
                            Model.Set(arrList[i], item[arrList[i].ToString()]);
                        }
                        List.Add(Model);
                    }
                    return List;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                Debug("获取列表数据GetList 失败 , 调用方法名 : GetListField", ex);
                throw ex;
            }
        }

        #endregion

        #region GetPage 方法 结果中包含总共多少条


        /// <summary>
        /// 获取Page Page不从0开始计算  从1开始计算
        /// 增加总条数参数
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="PageSize">页大小 最低为1</param>
        /// <param name="Where">where</param>
        /// <param name="CurPage">当前页 最低为1</param>
        /// <param name="OrderBy">排序默认使用 ID DESC (ID倒序排列)</param>
        /// <param name="IgnoreReleaseTime">是否忽略定时发布 , 用于后台 , true 为忽略定时发布条件 false 可以查找出所有的数据(包括未发布的数据)</param> 
        /// <returns></returns>
        public SysModel.PageModels GetPage(string TableName, int PageSize, int CurPage, string Where, string OrderBy, bool IgnoreReleaseTime = true)
        {
            return GetPageData(TableName, null, PageSize, CurPage, Where, OrderBy, IgnoreReleaseTime);
        }

        /// <summary>
        /// 获取Page Page不从0开始计算  从1开始计算
        /// 增加总条数参数
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Fields">要取的数据库字段</param>
        /// <param name="PageSize">页大小 最低为1</param>
        /// <param name="CurPage">当前页 最低为1</param>
        /// <param name="Where">条件</param>
        /// <param name="OrderBy">排序默认使用 ID DESC (ID倒序排列)</param>
        /// <param name="IgnoreReleaseTime">是否忽略定时发布 , 用于后台 , true 为忽略定时发布条件 false 可以查找出所有的数据(包括未发布的数据)</param> 
        /// <returns></returns>
        public SysModel.PageModels GetPage(string TableName, string Fields, int PageSize, int CurPage, string Where, string OrderBy, bool IgnoreReleaseTime = true)
        {
            return GetPageData(TableName, Fields, PageSize, CurPage, Where, OrderBy, IgnoreReleaseTime);
        }



        /// <summary>
        /// 获取Page Page不从0开始计算  从1开始计算
        /// 增加总条数参数
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Fields">要取的数据库字段</param>
        /// <param name="PageSize">页大小 最低为1</param>
        /// <param name="CurPage">当前页 最低为1</param>
        /// <param name="Where">where 条件 不用写where</param>
        /// <param name="OrderBy">排序默认使用 ID DESC (ID倒序排列)</param>
        /// <param name="IgnoreReleaseTime">是否忽略定时发布 , 用于后台 , true 为忽略定时发布条件 false 可以查找出所有的数据(包括未发布的数据)</param> 
        /// <returns></returns>
        private SysModel.PageModels GetPageData(string TableName, string Fields, int PageSize, int CurPage, string Where, string OrderBy, bool IgnoreReleaseTime = true)
        {

            try
            {

                #region 定时发布时间控制 , 这个判断主要用于后台查找内容
                if (IgnoreReleaseTime)
                {
                    if (new BLL.Base().GetHasReleaseTime(TableName))
                    {
                        //如果表支持定时发布 , 不用理会是否栏目支持定时发布 , 因为表中默认时间和发布时间是一样的
                        if (string.IsNullOrEmpty(Where))
                        {
                            Where = " PublishTime<=NOW() ";
                        }
                        else
                        {
                            Where = Where + " and  PublishTime<=NOW() ";
                        }
                    }
                }
                #endregion

                CurPage = CurPage == 0 ? 1 : CurPage;
                //TAB1.*
                string StrField = "";
                if (string.IsNullOrEmpty(Fields))
                {
                    StrField = "*";
                }

                StrField = StrField.TrimEnd(',');
                //string SqlStr = string.Format("SELECT {4} FROM {0} TAB1, (SELECT TOP {2} ROW_NUMBER() OVER (ORDER BY {1}) _SET_ROW_NUM_, ID FROM {0} {5} ) TAB2  WHERE TAB1.ID = TAB2.ID AND TAB2._SET_ROW_NUM_ > {3} {6};",
                string SqlStr = string.Format("SELECT {4} FROM {0} {5} ORDER BY {1} LIMIT {3},{2};",
                    TableName,
                    string.IsNullOrEmpty(OrderBy) ? "ID DESC" : OrderBy,
                    PageSize * CurPage,
                    PageSize * (CurPage - 1),
                    StrField,
                    string.IsNullOrEmpty(Where) ? "" : " Where " + Where
                    //string.IsNullOrEmpty(Where) ? "" : " AND " + Where
                    );

                SqlStr += string.Format("SELECT COUNT(ID)/{0} From {1} {2};", PageSize, TableName, string.IsNullOrEmpty(Where) ? "" : " Where " + Where);
                SqlStr += string.Format("SELECT COUNT(ID)%{0} From {1} {2};", PageSize, TableName, string.IsNullOrEmpty(Where) ? "" : " Where " + Where);
                ////Common.CommFun.WirteFile(SqlStr);
                //Evan.SystemLog.MemLog.AddExLog2("底层分页查询SQL  ", null, SqlStr);
                //分页查询完后总共有3张表
                //第一张表返回的是分页的数据
                //第二张表返回的是总条数/分页大小 结果
                //第三张表返回的是总跳水/分页大小的余数  如果余数>0 则分页+1 否则为刚好除尽
                DataSet ds = dbHelper.ExecuteDataSetText(SqlStr, null);
                //如果执行完不是返回3张表就返回null
                if (ds.Tables.Count != 3)
                {
                    return null;
                }
                DataTable dataTable = ds.Tables[0];
                int PageCount = Convert.ToInt32(Math.Floor(Convert.ToDecimal(ds.Tables[1].Rows[0][0]))); //分页数量
                int PageCount_More = Convert.ToInt32(ds.Tables[2].Rows[0][0]); //余数

                SysModel.PageModels page = new SysModel.PageModels();
                /*2017.06.27 张浩 修改 判断第二页的余数，如果大于0，则代表有余数，则页面加1。以前判断如果大于1，会出现分页数量为4，而总数为5，则会出现页码错误*/
                if (PageCount_More > 0)
                {
                    page.AllCount = PageCount * PageSize + PageCount_More;
                    PageCount = PageCount + 1;
                }
                else
                {
                    page.AllCount = PageCount * PageSize + PageCount_More;
                }


                page.PageCount = PageCount;
                page.CurPage = CurPage;
                page.PageSize = PageSize;

                page.Item = new List<dynamic>();
                if (page.AllCount <= 0)
                {
                    page.AllCount = 0;
                }
                if (dataTable != null)
                {
                    ArrayList arrList = new ArrayList();
                    if (string.IsNullOrEmpty(Fields))
                    {
                        //arrList = LoadDbSchema.GetColByDbAndTab(string.IsNullOrEmpty(DataBase) ? this.DataBase : DataBase, TableName);
                        foreach (var item in dataTable.Columns)
                        {
                            arrList.Add(item.ToString());
                        }
                    }
                    else
                    {
                        string[] arrList_Temp = Fields.Split(',');
                        arrList = new ArrayList(arrList_Temp);
                    }

                    List<dynamic> List = new List<dynamic>();
                    dynamic Model = null;
                    foreach (DataRow item in dataTable.Rows)
                    {
                        Model = new DynamicModel();
                        for (int i = 0; i < arrList.Count; i++)
                        {
                            Model.Set(arrList[i], item[arrList[i].ToString()]);
                        }
                        List.Add(Model);
                    }
                    ////Common.CommFun.WirteFile(List.Count.ToString());
                    page.Item = List;
                }
                else
                {
                    return null;
                }

                return page;
            }
            catch (Exception ex)
            {

                #region  记录错误
                Debug("获取列表数据GetPage 失败 , 调用方法名 : GetPageData", ex);
                throw ex;
                #endregion
            }
        }

        #endregion

        #region GetSearchPage 方法 获取搜索分页数据


        /// <summary>
        /// 获取搜索分页
        /// 获取Page Page不从0开始计算  从1开始计算
        /// 增加总条数参数
        /// </summary>
        /// <param name="PageSize">页大小 最低为1</param>
        /// <param name="CurPage">当前页 最低为1</param>
        /// <param name="OrderBy">排序默认使用 ID DESC (ID倒序排列)</param>
        /// <returns></returns>
        public SysModel.PageModels GetSearchPage(string TableName, int PageSize, int CurPage, string Where, string OrderBy)
        {
            return GetSearchPageData(TableName, null, PageSize, CurPage, Where, OrderBy);
        }

        /// <summary>
        /// 获取搜索分页
        /// 获取Page Page不从0开始计算  从1开始计算
        /// 增加总条数参数
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Fields">要取的数据库字段</param>
        /// <param name="PageSize">页大小 最低为1</param>
        /// <param name="CurPage">当前页 最低为1</param>
        /// <param name="Where">条件</param>
        /// <param name="OrderBy">排序默认使用 ID DESC (ID倒序排列)</param>
        /// <returns></returns>
        public SysModel.PageModels GetSearchPage(string TableName, string Fields, int PageSize, int CurPage, string Where, string OrderBy)
        {
            return GetSearchPageData(TableName, Fields, PageSize, CurPage, Where, OrderBy);
        }



        /// <summary>
        /// 获取搜索分页
        /// 获取Page Page不从0开始计算  从1开始计算
        /// 增加总条数参数
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Fields">要取的数据库字段</param>
        /// <param name="PageSize">页大小 最低为1</param>
        /// <param name="CurPage">当前页 最低为1</param>
        /// <param name="Where">where 条件 不用写where</param>
        /// <param name="OrderBy">排序默认使用 ID DESC (ID倒序排列)</param>
        /// <returns></returns>
        private SysModel.PageModels GetSearchPageData(string TableName, string Fields, int PageSize, int CurPage, string Where, string OrderBy)
        {

            try
            {

                #region 定时发布时间控制
                if (new BLL.Base().GetHasReleaseTime(TableName))
                {
                    //如果表支持定时发布 , 不用理会是否栏目支持定时发布 , 因为表中默认时间和发布时间是一样的
                    if (string.IsNullOrEmpty(Where))
                    {
                        Where = " PublishTime<=NOW() ";
                    }
                    else
                    {
                        Where = Where + " and  PublishTime<=NOW() ";
                    }
                }
                #endregion

                CurPage = CurPage == 0 ? 1 : CurPage;
                //TAB1.*
                string StrField = "";
                if (string.IsNullOrEmpty(Fields))
                {
                    StrField = "*";
                }
                StrField = StrField.TrimEnd(',');
                //string SqlStr = string.Format("SELECT {4} FROM {0} TAB1, (SELECT TOP {2} ROW_NUMBER() OVER (ORDER BY {1}) _SET_ROW_NUM_, ID,Guids FROM {0} {5} ) TAB2  WHERE TAB1.Guids = TAB2.Guids AND TAB2._SET_ROW_NUM_ > {3} {6};",
                //    TableName,
                //    string.IsNullOrEmpty(OrderBy) ? "ID DESC" : OrderBy,
                //    PageSize * CurPage,
                //    PageSize * (CurPage - 1),
                //    StrField,
                //    string.IsNullOrEmpty(Where) ? "" : " Where " + Where,
                //    string.IsNullOrEmpty(Where) ? "" : " AND " + Where
                //    );
                string SqlStr = string.Format("SELECT {4} FROM {0} {5} ORDER BY {1} LIMIT {3},{2};",
                    TableName,
                    string.IsNullOrEmpty(OrderBy) ? "ID DESC" : OrderBy,
                    PageSize * CurPage,
                    PageSize * (CurPage - 1),
                    StrField,
                    string.IsNullOrEmpty(Where) ? "" : " Where " + Where
                    );

                SqlStr += string.Format("SELECT COUNT(ID)/{0} From {1} {2};", PageSize, TableName, string.IsNullOrEmpty(Where) ? "" : " Where " + Where);
                SqlStr += string.Format("SELECT COUNT(ID)%{0} From {1} {2};", PageSize, TableName, string.IsNullOrEmpty(Where) ? "" : " Where " + Where);
                ////Common.CommFun.WirteFile(SqlStr);
                //Evan.SystemLog.MemLog.AddExLog2("底层分页查询SQL  ", null, SqlStr);
                //分页查询完后总共有3张表
                //第一张表返回的是分页的数据
                //第二张表返回的是总条数/分页大小 结果
                //第三张表返回的是总跳水/分页大小的余数  如果余数>0 则分页+1 否则为刚好除尽
                DataSet ds = dbHelper.ExecuteDataSetText(SqlStr, null);
                //如果执行完不是返回3张表就返回null
                if (ds.Tables.Count != 3)
                {
                    return null;
                }
                DataTable dataTable = ds.Tables[0];
                //int PageCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]); //分页数量
                int PageCount = Convert.ToInt32(Math.Floor(Convert.ToDecimal(ds.Tables[1].Rows[0][0]))); //分页数量
                int PageCount_More = Convert.ToInt32(ds.Tables[2].Rows[0][0]); //余数

                SysModel.PageModels page = new SysModel.PageModels();
                /*2017.06.27 张浩 修改 判断第二页的余数，如果大于0，则代表有余数，则页面加1。以前判断如果大于1，会出现分页数量为4，而总数为5，则会出现页码错误*/
                if (PageCount_More > 0)
                {
                    page.AllCount = PageCount * PageSize + PageCount_More;
                    PageCount = PageCount + 1;
                }
                else
                {
                    page.AllCount = PageCount * PageSize + PageCount_More;
                }


                page.PageCount = PageCount;
                page.CurPage = CurPage;
                page.PageSize = PageSize;

                page.Item = new List<dynamic>();
                if (page.AllCount <= 0)
                {
                    page.AllCount = 0;
                }
                if (dataTable != null)
                {
                    ArrayList arrList = new ArrayList();
                    if (string.IsNullOrEmpty(Fields))
                    {
                        //arrList = LoadDbSchema.GetColByDbAndTab(string.IsNullOrEmpty(DataBase) ? this.DataBase : DataBase, TableName);
                        foreach (var item in dataTable.Columns)
                        {
                            arrList.Add(item.ToString());
                        }
                    }
                    else
                    {
                        string[] arrList_Temp = Fields.Split(',');
                        arrList = new ArrayList(arrList_Temp);
                    }

                    List<dynamic> List = new List<dynamic>();
                    dynamic Model = null;
                    foreach (DataRow item in dataTable.Rows)
                    {
                        Model = new DynamicModel();
                        for (int i = 0; i < arrList.Count; i++)
                        {
                            Model.Set(arrList[i], item[arrList[i].ToString()]);
                        }
                        List.Add(Model);
                    }
                    ////Common.CommFun.WirteFile(List.Count.ToString());
                    page.Item = List;
                }
                else
                {
                    return null;
                }

                return page;
            }
            catch (Exception ex)
            {

                #region  记录错误
                Debug("获取列表数据GetPage 失败 , 调用方法名 : GetSearchPage", ex);
                throw ex;
                #endregion
            }
        }

        #endregion

        #region Insert 方法

        /// <summary>
        /// 新增一条数据 返回新增数据后的Model
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Model"></param>
        /// <returns></returns>
        public dynamic InsertReturnModel(string TableName, dynamic Model)
        {
            int Id = Insert(Model, TableName);
            if (Id > 0)
            {
                return GetModel(TableName, Id);
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 插入一条数据 返回新增数据的ID
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Model"></param>
        /// <returns></returns>
        public int InsertReturnId(string TableName, dynamic Model)
        {
            return Insert(Model, TableName);
        }

        /// <summary>
        /// 新增一条数据 返回新增数据后的ID
        /// </summary>
        /// <param name="Model"></param>
        /// <param name="TableName"></param>
        /// <returns></returns>
        private int Insert(dynamic Model, string TableName)
        {

            string SqlStr = "INSERT INTO {0} ({1}) values ({2}) ";
            string Fields = "";
            string Vaules = "";
            ArrayList objList = new ArrayList();
            foreach (var property in (Dictionary<string, object>)Model._Map_In_Dictionary)
            {
                if (property.Key.ToUpper() == "ID")
                {
                    continue;
                }
                Fields += "" + property.Key + ",";
                Vaules += "@" + property.Key + ",";
                objList.Add(property.Value);
            }
            object[] param = new object[objList.Count];
            for (int i = 0; i < objList.Count; i++)
            {
                param[i] = objList[i];
            }
            SqlStr = string.Format(SqlStr, TableName, Fields.TrimEnd(','), Vaules.TrimEnd(','));
            MySqlParameter[] parameter = dbHelper.GetSqlParameterBySqlStr(SqlStr, param);
            SqlStr += ";SELECT LAST_INSERT_ID();";

            try
            {
                var newid = Convert.ToInt32(dbHelper.ExecuteScalarText(SqlStr, parameter));

                if (IsExistField(TableName, "Guids") && IsExistField(TableName, "SortId"))
                {
                    //充当触发器
                    dbHelper.ExecuteScalarText($"UPDATE `{TableName}` set Guids = UUID(),SortId = {newid} WHERE Id = {newid}");
                }

                return newid;
            }
            catch (Exception ex)
            {
                Debug("添加数据Insert 失败 , 调用方法名 : Insert", ex);
                throw ex;
            }
        }

        #endregion


        #region Update 方法

        /// <summary>
        /// 更新字段  注意SQL字段和参数必须顺序正确
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Fields">字段 Title=@Title</param>
        /// <param name="Where">条件 Id=@Id</param>
        /// <param name="param">"TItle",Id</param>
        /// <returns></returns>
        public bool UpdateFields(string TableName, string Fields, string Where, params object[] param)
        {
            return Update(TableName, Fields, Where, param);
        }

        /// <summary>
        /// 根据Id更新一个Model
        /// </summary>
        /// <param name="TableName">表名称</param>
        /// <param name="Model">动态Model</param>
        /// <returns></returns>
        public bool Update(string TableName, dynamic Model)
        {

            ArrayList objList = new ArrayList();
            string SetStr = "";
            int Id = 0;
            foreach (var property in (Dictionary<string, object>)Model._Map_In_Dictionary)
            {
                if (property.Key.ToUpper() == "ID")
                {
                    Id = Convert.ToInt32(property.Value);
                    continue;
                }
                SetStr += "" + property.Key + "=@" + property.Key + ",";
                objList.Add(property.Value);
            }

            object[] param = new object[objList.Count + 1];
            for (int i = 0; i < objList.Count; i++)
            {
                param[i] = objList[i];
            }
            param[objList.Count] = Id;

            return Update(TableName, SetStr, "Id=@Id", param);
        }
        /// <summary>
        /// 更新方法
        /// </summary>
        /// <param name="TableName">表名称</param>
        /// <param name="Fields">更新的字段值  不能为空</param>
        /// <param name="Where">更新条件 不能为空</param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        private bool Update(string TableName, string Fields, string Where, params object[] param)
        {

            Fields = Fields.TrimEnd(',');
            string SqlStr = string.Format("UPDATE {0} SET {1} WHERE {2}",
                TableName,
                Fields,
                Where
                );
            MySqlParameter[] parameter = dbHelper.GetSqlParameterBySqlStr(SqlStr, param);
            try
            {
                int IsOk = dbHelper.ExecteNonQueryText(SqlStr, parameter);
                return IsOk > 0 ? true : false;
            }
            catch (Exception ex)
            {
                Debug("更新数据Update 失败 , 调用方法名 : Update", ex);
                throw ex;
            }
        }
        #endregion

        #region Delete 方法

        /// <summary>
        /// 数据库删除
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Where"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public bool Delete(string TableName, string Where, params object[] param)
        {
            return Deletes(TableName, Where, param);
        }

        /// <summary>
        /// 虚拟删除  [Status]=-1
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Where"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public bool Delete_Virtual(string TableName, string Where, params object[] param)
        {
            return UpdateFields(TableName, "States=-1", Where, param);
        }
        /// <summary>
        /// 虚拟删除  [Status]=-1
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Id"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public bool Delete_Virtual(string TableName, int Id, params object[] param)
        {
            return UpdateFields(TableName, "States=-1", "Id=@Id", Id);
        }
        /// <summary>
        /// 删除数据 , 数据库删除
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Where"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        private bool Deletes(string TableName, string Where, params object[] param)
        {
            string SqlStr = string.Format("DELETE FROM {0} WHERE {1}", TableName, Where);
            MySqlParameter[] parameter = dbHelper.GetSqlParameterBySqlStr(SqlStr, param);
            try
            {
                int IsOk = dbHelper.ExecteNonQueryText(SqlStr, parameter);
                //此处代码屏蔽 张澎 2019年1月24日16:16:13   如果没有数据可以删除 , 那0就返回错了 , 所以屏蔽 , 只要没出错就默认处理成功
                //return IsOk > 0 ? true : false;   
                return true;
            }
            catch (Exception ex)
            {
                Debug("删除数据Delete 失败 , 调用方法名 : Deletes", ex);
                throw ex;
            }
        }
        #endregion

        #region 获取上下一条的方法
        /// <summary>
        /// 获取上一条数据的方法
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Model"></param>
        /// <param name="Order"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public dynamic GetPrev(string TableName, dynamic Model, string Order, params object[] param)
        {
            return GetPrevModel(TableName, null, Model.Id, Model.CatId, Order, param);
        }

        /// <summary>
        /// 获取上一条数据
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Fields"></param>
        /// <param name="DocumentId"></param>
        /// <param name="CatId"></param>
        /// <param name="Order"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        private dynamic GetPrevModel(string TableName, string Fields, int DocumentId, int CatId, string Order, params object[] param)
        {

            string SqlStr = string.Format("select {0} from {1} where id = (select max(id) from {1} where id < {2} and CatId={4} order by {3}) and CatId={4} order by {3};",
                string.IsNullOrEmpty(Fields) ? "*" : Fields,
                TableName,
                DocumentId,
                string.IsNullOrEmpty(Order) ? "SortId asc,AddTime desc" : Order,
                CatId
                );


            try
            {


                MySqlParameter[] parameter = dbHelper.GetSqlParameterBySqlStr(SqlStr, param);

                DataRow dr = dbHelper.GetSingle(SqlStr, parameter);
                dynamic Model = null;
                if (dr != null)
                {
                    Model = new DynamicModel();
                    //ArrayList arrList = LoadDbSchema.GetColsByTab(string.IsNullOrEmpty(DataBase) ? this.DataBase : DataBase, TableName);
                    ArrayList arrList = new ArrayList();
                    foreach (var item in dr.Table.Columns)
                    {
                        arrList.Add(item.ToString());
                    }

                    foreach (string item in arrList)
                    {
                        Model.Set(item, dr[item]);
                    }
                }
                return Model;
            }
            catch (Exception ex)
            {
                Debug("获取上一条数据GetPrevModel 失败 , 调用方法名 : ", ex);
                throw ex;
            }

        }

        /// <summary>
        /// 获取下一跳数据的方法
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Model"></param>
        /// <param name="Order"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public dynamic GetNext(string TableName, dynamic Model, string Order, params object[] param)
        {
            return GetNextModel(TableName, null, Model.Id, Model.CatId, Order, param);
        }

        /// <summary>
        /// 获取下一跳数据
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Fields"></param>
        /// <param name="DocumentId"></param>
        /// <param name="CatId"></param>
        /// <param name="Order"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        private dynamic GetNextModel(string TableName, string Fields, int DocumentId, int CatId, string Order, params object[] param)
        {

            string SqlStr = string.Format("select {0} from {1} where id = (select min(id) from {1} where id > {2} and CatId={4} order by {3}) and CatId={4} order by {3};",
                string.IsNullOrEmpty(Fields) ? "*" : Fields,
                TableName,
                DocumentId,
                string.IsNullOrEmpty(Order) ? "SortId asc,AddTime desc" : Order,
                CatId
                );
            try
            {


                MySqlParameter[] parameter = dbHelper.GetSqlParameterBySqlStr(SqlStr, param);
                DataRow dr = dbHelper.GetSingle(SqlStr, parameter);
                dynamic Model = null;
                if (dr != null)
                {
                    Model = new DynamicModel();
                    //ArrayList arrList = LoadDbSchema.GetColsByTab(string.IsNullOrEmpty(DataBase) ? this.DataBase : DataBase, TableName);
                    ArrayList arrList = new ArrayList();
                    foreach (var item in dr.Table.Columns)
                    {
                        arrList.Add(item.ToString());
                    }

                    foreach (string item in arrList)
                    {
                        Model.Set(item, dr[item]);
                    }

                }
                return Model;
            }
            catch (Exception ex)
            {
                Debug("获取下一条数据GetNextModel 失败 , 调用方法名 : GetNextModel", ex);
                throw ex;
            }
        }

        #endregion


        #region 事务操作
        /// <summary>
        /// 事务操作 , 传入的SQL语句至少需要一条
        /// </summary>
        /// <param name="SqlStrList"></param>
        /// <returns></returns>
        public bool ExecuteTransaction(List<string> SqlStrList)
        {
            if (SqlStrList.Count < 1)
            {
                Debug("执行事务的SQL列表不能小于1条", "");
                return false;
            }
            bool result = false;
            try
            {
                dbHelper.ExecuteTransaction(SqlStrList);
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
                Debug("ExecuteTransaction",ex);
            }
            return result;
        }
        #endregion


        #region 复制数据
        /// <summary>
        /// 复制一条数据 . 被复制的表如果没有字段会报错   注意字段大小写区别 
        /// </summary>
        /// <param name="TableName">表名称</param>
        /// <param name="Id">标识列</param>
        /// <param name="CusFields">如果有表是需要自己设置字段的需要单独处理</param>
        /// <returns></returns>
        public int CopyData(string TableName, string Id, Dictionary<string, string> CusFields)
        {
            //复制一条数据
            //先拿到该条数据的字段 ,Fields,
            string SqlStr_GetFieldList = string.Format("select group_concat(COLUMN_NAME) FieldList from information_schema.COLUMNS where table_name = '{0}'", TableName);
            string FieldList = dbHelper.ExecuteScalar(CommandType.Text, SqlStr_GetFieldList, null).ToString();
            FieldList = "," + FieldList + ",";
            //替换其中可能出现的自动生成的字段 Id Guids AddUser AddTime EditUser EditTime
            FieldList = FieldList.Replace(",Id,", ",").Replace(",Guids,", ",").Replace(",AddUser,", ",").Replace(",AddTime,", ",").Replace(",EditUser,", ",").Replace(",EditTime,", ",");
            //FieldList 是插入的字段表   FieldSelect 是选择的字符列表
            string FieldSelect = FieldList;
            //如果有表是需要自己设置字段的需要单独处理
            if (CusFields != null)
            {
                foreach (var item in CusFields)
                {
                    if (FieldList.Contains("," + item.Key + ",")) //如果包含字段
                    {
                        FieldSelect = FieldSelect.Replace("," + item.Key + ",", ",'" + item.Value + "' as " + item.Key + ",");
                    }
                }
            }
            FieldList = FieldList.Trim(',');
            FieldSelect = FieldSelect.Trim(',');
            //Insert Into Channel (ParentId,Title,SubClass,SubTitle,EnTitle,Deep,ManagePageUrl,WebPath) select '1' as ParentId,Title,SubClass,SubTitle,EnTitle,Deep,ManagePageUrl,WebPath from Channel where Id=42
            string SqlStr_Insert = string.Format("Insert Into {0} ({1}) select {2} from {0} where Id={3}; SELECT @@IDENTITY;", TableName, FieldList, FieldSelect, Id);

            try
            {
                int IsOk = Convert.ToInt32(dbHelper.ExecuteScalarText(SqlStr_Insert, null));
                return IsOk;
            }
            catch (Exception ex)
            {
                Debug("复制数据CopyData 失败 , 调用方法名 : CopyData", ex);
                throw ex;
            }
        }

        /// <summary>
        /// 复制字段表多条数据 . 被复制的表如果没有字段会报错   注意字段大小写区别 
        /// </summary>
        /// <param name="TableName">表名称</param>
        /// <param name="CategoryId">栏目表的ID</param>
        /// <param name="CusFields">需要替换的字段值 key=字段 value=值</param>
        /// <returns></returns>
        public bool CopyChannelFields(string TableName, string CategoryId, Dictionary<string, string> CusFields)
        {
            try
            {
                //先检查被复制的栏目中字段是否为空 如果为空直接返回成功
                string CheckHasFieldsSqlStr = string.Format("SELECT COUNT(Id) FROM Fields WHERE ClassId={0}", CategoryId);
                int FieldsCount = Convert.ToInt32(dbHelper.ExecuteScalar(CommandType.Text, CheckHasFieldsSqlStr, null));
                if (FieldsCount == 0)
                {
                    return true;
                }

                //复制一条数据
                //先拿到该条数据的字段 ,Fields,
                string SqlStr_GetFieldList = string.Format("select group_concat(COLUMN_NAME) FieldList from information_schema.COLUMNS where table_name = '{0}'", TableName);
                string FieldList = dbHelper.ExecuteScalar(CommandType.Text, SqlStr_GetFieldList, null).ToString();
                FieldList = "," + FieldList + ",";
                //替换其中可能出现的自动生成的字段 Id Guids AddUser AddTime EditUser EditTime
                FieldList = FieldList.Replace(",Id,", ",").Replace(",Guids,", ",").Replace(",AddUser,", ",").Replace(",AddTime,", ",").Replace(",EditUser,", ",").Replace(",EditTime,", ",");
                //FieldList 是插入的字段表   FieldSelect 是选择的字符列表
                string FieldSelect = FieldList;
                //如果有表是需要自己设置字段的需要单独处理

                if (CusFields != null)
                {
                    foreach (var item in CusFields)
                    {

                        if (FieldList.Contains("," + item.Key + ",")) //如果包含字段
                        {
                            FieldSelect = FieldSelect.Replace("," + item.Key + ",", ",'" + item.Value + "' as " + item.Key + ",");
                        }
                    }
                }
                FieldList = FieldList.Trim(',');
                FieldSelect = FieldSelect.Trim(',');
                //Insert Into Channel (ParentId,Title,SubClass,SubTitle,EnTitle,Deep,ManagePageUrl,WebPath) select '1' as ParentId,Title,SubClass,SubTitle,EnTitle,Deep,ManagePageUrl,WebPath from Channel where Id=42
                string SqlStr_Insert = string.Format("Insert Into {0} ({1}) select {2} from {0} where ClassId={3}", TableName, FieldList, FieldSelect, CategoryId);

                //Evan.//Common.CommFun.WirteFile("CopyChannelFields:" + SqlStr_Insert + "");

                int IsOk = dbHelper.ExecteNonQueryText(SqlStr_Insert, null);
                return IsOk > 0 ? true : false;
            }
            catch (Exception ex)
            {
                Debug("复制栏目字段失败 , 请检查被复制的表 字段是否为空 , 调用方法名 : CopyChannelFields", ex);
                throw ex;
            }
        }

        /// <summary>
        /// 复制栏目里面的内容 
        /// <para>复制栏目的时候选择了复制数据,  则可以将被复制的栏目里面的数据也都Copy过来</para>
        /// </summary>
        /// <param name="TableName">栏目内容所属表</param>
        /// <param name="CategoryId">栏目CategoryId</param>
        /// <param name="CusFields">自定义需要复制的字段</param>
        /// <returns></returns>
        public bool CopyChannelData(string TableName, string CategoryId, Dictionary<string, string> CusFields)
        {
            try
            {
                //复制一条数据 
                //先拿到该条数据的字段 ,Fields,
                string SqlStr_GetFieldList = string.Format("select group_concat(COLUMN_NAME) FieldList from information_schema.COLUMNS where table_name = '{0}'", TableName);
                string FieldList = dbHelper.ExecuteScalar(CommandType.Text, SqlStr_GetFieldList, null).ToString();
                FieldList = "," + FieldList + ",";
                //替换其中可能出现的自动生成的字段 Id Guids AddUser AddTime EditUser EditTime
                FieldList = FieldList.Replace(",Id,", ",").Replace(",Guids,", ",").Replace(",AddUser,", ",").Replace(",AddTime,", ",").Replace(",EditUser,", ",").Replace(",EditTime,", ",");
                //FieldList 是插入的字段表   FieldSelect 是选择的字符列表
                string FieldSelect = FieldList;
                //如果有表是需要自己设置字段的需要单独处理

                if (CusFields != null)
                {
                    foreach (var item in CusFields)
                    {

                        if (FieldList.Contains("," + item.Key + ",")) //如果包含字段
                        {
                            FieldSelect = FieldSelect.Replace("," + item.Key + ",", ",'" + item.Value + "' as " + item.Key + ",");
                        }
                    }
                }
                FieldList = FieldList.Trim(',');
                FieldSelect = FieldSelect.Trim(',');
                //Insert Into Channel (ParentId,Title,SubClass,SubTitle,EnTitle,Deep,ManagePageUrl,WebPath) select '1' as ParentId,Title,SubClass,SubTitle,EnTitle,Deep,ManagePageUrl,WebPath from Channel where Id=42
                string SqlStr_Insert = string.Format("Insert Into {0} ({1}) select {2} from {0} where ClassId={3}", TableName, FieldList, FieldSelect, CategoryId);

                //Evan.//Common.CommFun.WirteFile("CopyChannelFields:" + SqlStr_Insert + "");
                //Evan.SystemLog.MemLog.AddExLog2("复制栏目后复制内容SQL : ", null, SqlStr_Insert);
                int IsOk = dbHelper.ExecteNonQueryText(SqlStr_Insert, null);
                return IsOk > 0 ? true : false;
            }
            catch (Exception ex)
            {
                Debug("复制栏目后复制内容失败 (复制栏目时选择了内容复制)", ex);
                throw ex;
            }
        }

        /// <summary>
        /// 复制模板表多条数据 . 被复制的表如果没有字段会报错   注意字段大小写区别 
        /// <para>复制模板的时候需要复制模板对应的Model</para>
        /// </summary>
        /// <param name="TableName">表名称</param>
        /// <param name="CategoryId">栏目表的ID</param>
        /// <param name="CusModules"></param>
        /// <returns></returns>
        public bool CopyChannelModules(string TableName, string CategoryId, Dictionary<string, string> CusModules)
        {
            try
            {
                //复制一条数据
                //先拿到该条数据的字段 ,Fields,
                string SqlStr_GetFieldList = string.Format("select group_concat(COLUMN_NAME) FieldList from information_schema.COLUMNS where table_name = '{0}'", TableName);
                string FieldList = dbHelper.ExecuteScalar(CommandType.Text, SqlStr_GetFieldList, null).ToString();
                FieldList = "," + FieldList + ",";
                //替换其中可能出现的自动生成的字段 Id Guids AddUser AddTime EditUser EditTime
                FieldList = FieldList.Replace(",Id,", ",").Replace(",Guids,", ",").Replace(",AddUser,", ",").Replace(",AddTime,", ",").Replace(",EditUser,", ",").Replace(",EditTime,", ",");
                //FieldList 是插入的字段表   FieldSelect 是选择的字符列表
                string FieldSelect = FieldList;
                //如果有表是需要自己设置字段的需要单独处理

                if (CusModules != null)
                {
                    foreach (var item in CusModules)
                    {

                        if (FieldList.Contains("," + item.Key + ",")) //如果包含字段
                        {
                            FieldSelect = FieldSelect.Replace("," + item.Key + ",", ",'" + item.Value + "' as " + item.Key + ",");
                        }
                    }
                }
                FieldList = FieldList.Trim(',');
                FieldSelect = FieldSelect.Trim(',');
                //Insert Into Channel (ParentId,Title,SubClass,SubTitle,EnTitle,Deep,ManagePageUrl,WebPath) select '1' as ParentId,Title,SubClass,SubTitle,EnTitle,Deep,ManagePageUrl,WebPath from Channel where Id=42
                string SqlStr_Insert = string.Format("Insert Into {0} ({1}) select {2} from {0} where ChannelId={3}", TableName, FieldList, FieldSelect, CategoryId);

                int IsOk = dbHelper.ExecteNonQueryText(SqlStr_Insert, null);
                return IsOk > 0 ? true : false;
            }
            catch (Exception ex)
            {
                Debug("复制栏目字段CopyChannelModules 失败 , 请检查被复制的表 字段是否为空", ex);
                throw ex;
            }
        }

        #endregion 

        #region 验证表或者数据库是否存在
        /// <summary>
        /// IsExistTable 表是否存在 
        /// </summary>
        /// <param name="TableName">表名称</param>
        /// <returns>是否存在 true 存在  false 不存在</returns>
        public bool IsExistTable(string TableName)
        {
            return IsExistTable(null, TableName);
        }
        /// <summary>
        /// IsExistTable 表是否存在 
        /// </summary>
        /// <param name="DataBase"> 链接字符串 为空标示使用实例化当前DbOperat的数据库</param>
        /// <param name="TableName">表名称</param>
        /// <returns>是否存在 true 存在  false 不存在</returns>
        public bool IsExistTable(string DataBase, string TableName)
        {
            DbHelper DbHelper2;
            if (string.IsNullOrEmpty(DataBase))
            {
                DbHelper2 = new DbHelper(this.ConnName);
            }
            else
            {
                DbHelper2 = new DbHelper(DataBase);
            }
            //int IsExist = DbHelp.ExecteNonQuery(CommandType.Text, "select * from sys.objects where name = '@TableName'", new SqlParameter("@TableName", TableName));
            int IsExist = DbHelper2.ExecteNonQuery(CommandType.Text, string.Format("SHOW TABLES LIKE '{0}';", TableName), null);
            return IsExist > 0 ? true : false;
        }


        /// <summary>
        /// 检查表中是否有当前字段 使用当前实例的数据库
        /// </summary>
        /// <param name="TableName">表名称</param>
        /// <param name="Field">字段名称</param>
        /// <returns>是否存在 true 存在  false 不存在</returns>
        public bool IsExistField(string TableName, string Field)
        {
            return IsExistField(null, TableName, Field);
        }
        /// <summary>
        /// 检查表中是否有当前字段
        /// </summary>
        /// <param name="DataBase">数据库链接字符串</param>
        /// <param name="TableName">表名称</param>
        /// <param name="Field">字段名称</param>
        /// <returns>是否存在 true 存在  false 不存在</returns>
        public bool IsExistField(string DataBase, string TableName, string Field)
        {
            DbHelper DbHelper2;
            if (string.IsNullOrEmpty(DataBase))
            {
                DbHelper2 = new DbHelper(this.ConnName);
            }
            else
            {
                DbHelper2 = new DbHelper(DataBase);
            }
            object obj = DbHelper2.ExecuteScalar(CommandType.Text, string.Format("select count(*) from information_schema.columns where table_name = '{0}' and column_name = '{1}'", TableName, Field), null);
            int IsExist = Convert.ToInt32(obj);
            return IsExist > 0 ? true : false;

        }
        #endregion

        #region 数据库字段操作

        /// <summary>
        /// 获取添加一个字段的SQL
        /// </summary>
        /// <param name="FieldModel"></param>
        /// <returns></returns>
        private string GetCreateFieldSql(SysModel.FieldModel FieldModel)
        {
            StringBuilder CreateFieldSql = new StringBuilder();
            //alter table Ads add Title1 nvarchar(100) not null
            CreateFieldSql.Append("ALTER TABLE ");
            CreateFieldSql.Append(FieldModel.TableName);
            CreateFieldSql.Append(" ADD ");
            CreateFieldSql.Append(FieldModel.FieldName);


            #region 字段类型 如果不是在指定类型的话就默认为nvarchar
            //string[] FieldType = { "int", "nvarchar", "datetime", "decimal(18, 2)" };
            string[] FieldType = { "number", "string", "datetime", "text", "price" };

            switch (FieldModel.FieldType.ToLower())
            {
                case "number":
                    CreateFieldSql.Append(" int ");
                    break;
                case "string":
                    CreateFieldSql.Append(" text ");
                    FieldModel.FieldDefault = "";
                    break;
                case "datetime":
                    CreateFieldSql.Append(" datetime ");
                    break;
                case "text":
                    CreateFieldSql.Append(" mediumtext ");
                    FieldModel.FieldDefault = "";
                    break;
                case "price":
                    CreateFieldSql.Append(" decimal(18, 2) ");
                    break;
                default:
                    CreateFieldSql.Append(" text ");
                    FieldModel.FieldDefault = "";
                    break;
            }

            //if (FieldType.Contains(FieldModel.FieldType.ToLower()))
            //{
            //    //CreateFieldSql.Append(" " + FieldModel.FieldType + " ");

            //}
            //else
            //{
            //    CreateFieldSql.Append(" nvarchar ");
            //}
            #endregion

            #region 字段大小 只有 nvarchar 才能指定数据大小   nvarchar-max 代替 ntext
            //if (FieldModel.FieldType.ToLower() == "nvarchar")
            //{
            //    CreateFieldSql.Append(" (" + (FieldModel.FieldLength > 0 ? FieldModel.FieldLength.ToString() : "4000") + ") ");
            //}
            //if (FieldModel.FieldType.ToLower() == "nvarchar-max")
            //{
            //    CreateFieldSql.Append(" (max) ");
            //}

            #endregion

            #region 字段是否为空
            if (FieldModel.NotNull)
            {
                //CreateFieldSql.Append(" not null ");
            }
            #endregion

            #region 字段默认值
            //如果默认值为空则为系统默认的默认值
            if (string.IsNullOrEmpty(FieldModel.FieldDefault))
            {
                switch (FieldModel.FieldType.ToLower())
                {
                    case "number":
                        CreateFieldSql.Append(" Default 0 ");
                        break;
                    case "string":
                        //BLOB/TEXT column 'mytst1' can't have a default value
                        //CreateFieldSql.Append(" Default '' ");
                        break;
                    case "datetime":
                        CreateFieldSql.Append(" Default NOW() ");
                        break;
                    case "text":
                        //BLOB/TEXT column 'mytst1' can't have a default value
                        //CreateFieldSql.Append(" Default '' ");
                        break;
                    case "price":
                        CreateFieldSql.Append(" Default 0 ");
                        break;
                    default:
                        //BLOB/TEXT column 'mytst1' can't have a default value
                        //CreateFieldSql.Append(" Default '' ");
                        break;
                }
            }
            else
            {
                CreateFieldSql.Append(" Default " + FieldModel.FieldDefault + " ");
            }
            #endregion

            //Loger.Info(CreateFieldSql.ToString());

            return CreateFieldSql.ToString();
        }

        /// <summary>
        /// 添加字段到默认数据库的指定表
        /// </summary>
        /// <param name="FieldModel"></param>
        /// <returns></returns>
        public bool AddFieldToTable(SysModel.FieldModel FieldModel)
        {
            return AddFieldToTable(null, FieldModel);
        }

        /// <summary>
        /// 添加字段到指定数据库的指定表
        /// </summary>
        /// <param name="DataBase"></param>
        /// <param name="FieldModel"></param>
        /// <returns></returns>
        public bool AddFieldToTable(string DataBase, SysModel.FieldModel FieldModel)
        {
            DbHelper DbHelper2;
            if (string.IsNullOrEmpty(DataBase))
            {
                DbHelper2 = new DbHelper(this.ConnName);
            }
            else
            {
                DbHelper2 = new DbHelper(DataBase);
            }

            try
            {
                DbHelper2.ExecteNonQuery(CommandType.Text, GetCreateFieldSql(FieldModel), null); // 增加一张表
                return true;
            }
            catch
            {
                return false;
            }

        }

        #endregion

        #region  数据库备份
        /// <summary>
        /// 
        /// </summary>
        /// <param name="connName"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public bool BackUpDataBase(string connName = "", string filePath = "")
        {
            bool result = false;
            try
            {
                bool isok = dbHelper.BackUpDataBase(connName, filePath);
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
                Debug("数据库备份出错", ex);
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="title"></param>
        /// <param name="message"></param>
        public void Debug(string title, dynamic message)
        {
            Common.CommFun.Debug(title, message.ToString());
        }
        #endregion


        #region 直接执行SQL语句
        /// <summary>
        /// 执行SQL语句 返回List
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public DataTable ExecSqlCmd_Table(string sql, params object[] param)
        {
            MySqlParameter[] parameter = dbHelper.GetSqlParameterBySqlStr(sql, param);
            DataTable dataTable = dbHelper.GetFirstTable(sql, parameter);
            return dataTable;
        }

        /// <summary>
        /// 执行SQL语句 返回单行数据
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public DataRow ExecSqlCmd_Row(string sql, params object[] param)
        {
            MySqlParameter[] parameter = dbHelper.GetSqlParameterBySqlStr(sql, param);
            DataRow dr = dbHelper.GetSingle(sql, parameter);
            return dr;
        }

        /// <summary>
        /// 执行SQL语句 返回第一行第一列
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public object ExecSqlCmd_Object(string sql, params object[] param)
        {
            MySqlParameter[] parameter = dbHelper.GetSqlParameterBySqlStr(sql, param);
            object obj = dbHelper.ExecuteScalarText(sql, parameter);
            return obj;
        }

        /// <summary>
        /// 执行SQL语句 返回是否执行成功
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public int ExecSqlCmd_NonQuery(string sql, params object[] param)
        {
            MySqlParameter[] parameter = dbHelper.GetSqlParameterBySqlStr(sql, param);
            int res = dbHelper.ExecteNonQueryText(sql, parameter);
            return res;
        }
        #endregion

        #region 直接执行存储过程
        /// <summary>
        /// 执行SQL存储过程 返回List
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public DataTable ExecSqlProceducre_Table(string sql, params object[] param)
        {
            MySqlParameter[] parameter = dbHelper.GetSqlParameterBySqlStr(sql, param);
            DataTableCollection dt_Collection = dbHelper.GetTableProducts(sql, parameter);
            if (dt_Collection != null && dt_Collection.Count > 0)
            {
                return dt_Collection[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 执行SQL存储过程 返回单行数据
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataRow ExecSqlProceducre_Row(string sql, params object[] param)
        {
            DataTable dt = ExecSqlProceducre_Table(sql, param);
            if (dt == null || dt.Rows.Count > 0)
            {
                return dt.Rows[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 执行SQL存储过程 返回第一行第一列
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public object ExecSqlProceducre_Object(string sql, params object[] param)
        {
            MySqlParameter[] parameter = dbHelper.GetSqlParameterBySqlStr(sql, param);
            return dbHelper.ExecuteScalarProducts(sql, parameter); ;
        }

        /// <summary>
        /// 执行SQL存储过程 返回是否执行成功
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public int ExecSqlProceducre_NonQuery(string sql, params object[] param)
        {
            MySqlParameter[] parameter = dbHelper.GetSqlParameterBySqlStr(sql, param);
            return dbHelper.ExecteNonQueryProducts(sql, parameter); ;
        }
        #endregion


    }
}
